import React, { useImperativeHandle, forwardRef, useState, useEffect } from 'react'
import { Form, AutoComplete, Input, Select } from 'antd'
import { $get } from '@js/authRequest'

const { Item } = Form
const { TextArea } = Input
const { Option } = Select

// 获取请求内容
export async function getContentRequest (data) {
  const res = await $get('/api/xapc/deliver/getDeliverContent', data)
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

// 获取送达内容
// async function getContent (formRef, pState) {
//   const c = formRef.current
//   const data = c.getFieldsValue()
//   const [e, d] = await awaitWrap(getContentRequest({
//     action_subject: data.action_subject,
//     topic_type: pState.theme.type,
//     subject_type: data.subject_type
//   }))
//   if (e) {
//     return message.error(e.message)
//   }
//   formRef.current.setFieldsValue({ content: d })
// }

// 改变地址
function changeAddress (formRef, o, pState) {
  // getContent(formRef, pState)
  setTimeout(() => {
    formRef.current.setFieldsValue({
      contract: o.contract || undefined,
      addressid: o.id || undefined,
      type: o.type || undefined,
      zip_code: o.zip_code || undefined,
      structure: o.structure || undefined,
      mobile: o.mobile || undefined,
      tel: o.tel || undefined,
      tel_office: o.tel_office || undefined,
      address: o.address || undefined,
      email: o.email || undefined
    })
  }, 0)
}

function Main ({ addressList, formRef, pState, required = true }, ref) {
  const [types, setTypes] = useState([])
  useEffect(() => {
    setTypes(pState.dictionaries['送达地址类型'] || [])
  }, [pState.dictionaries])
  useImperativeHandle(ref, () => ({
    changeAddress
  }))
  return (
    <>
      <Item name='address' label='地址' rules={[{ required: true, message: '地址不能为空' }]}>
        <AutoComplete options={addressList} onSelect={(value, option) => changeAddress(formRef, option, pState)}>
          <TextArea rows={3} placeholder='请输入地址' />
        </AutoComplete>
      </Item>
      <Item name='type' label='地址类型' rules={[{ required, message: '地址类型不能为空' }]}>
        <Select placeholder='请选择地址类型'>
          {
            types.map(li => {
              return <Option key={li.title} value={li.title}>{li.title}</Option>
            })
          }
        </Select>
      </Item>
    </>
  )
}

export default forwardRef(Main)
